import os
import sys
import traceback


# Used for multiprocessing queue (producer / consumer)
# (type, value) has 2 forms:
# - (QUEUE_ELEMENT, row)
# - (QUEUE_END, None)
QueueElement = namedtuple('QueueElement', 'type value')
QUEUE_ELEMENT = 0
QUEUE_END = 1


def logwrapper(function, args, unpack=False):
    """Log wrapper function. It surrounds the call of the given function by a try/except and log the error if any."""

    try:
        if unpack:
            return function(*args)
        else:
            return function(args)
    except:
        print >> sys.strerr, '[pid:%d] Unexpected error:\n%s' % (os.getpid(), traceback.format_exc())
        raise

